<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/

namespace app\admin\controller\store;

use app\admin\model\User;
use app\common\controller\Backend;
use app\common\manager\EmployeeManager;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 门店员工管理
 *
 * @icon fa fa-circle-o
 */
class Employee extends Backend
{

    /**
     * Employee模型对象
     * @var \app\admin\model\store\Employee
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\store\Employee;
        $this->view->assign("isGroupList", $this->model->getIsGroupList());
        $this->view->assign("isWriteList", $this->model->getIsWriteList());
    }



    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        $storeId = $this->request->param("ids");
        $sid = $this->request->param("sid");
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['user','merchant','store'])
                    ->where($where)
                    ->where(function ($query) use ($sid) {
                        if ($sid){
                            return $query->where('store_id',$sid);
                        }
                    })
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        $this->assign('storeId', $storeId);
        return $this->view->fetch();
    }

    public function add()
    {
        $storeId = $this->request->get("storeId");
        if (false === $this->request->isPost()) {
            $this->assign("storeId", $storeId);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $data = [
                'mobile' => User::where('id',$params['user_id'])->value('mobile') ?? '',
                'real_name' => $params['real_name'],
                'is_group' => $params['is_group'],
                'is_write' => $params['is_write'],
            ];
            $results = EmployeeManager::employeeSys($data,$storeId,false);
            if ($results['code'] != EmployeeManager::$successCode){
                throw new Exception($results['message']);
            }
            $result = true;
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $data = [
                'mobile' => User::where('id',$params['user_id'])->value('mobile') ?? '',
                'real_name' => $params['real_name'],
                'is_group' => $params['is_group'],
                'is_write' => $params['is_write'],
            ];
            $results = EmployeeManager::modifySys($ids,$data,$row->store_id,false);
            if ($results['code'] != EmployeeManager::$successCode){
                throw new Exception($results['message']);
            }
            $result = true;
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    public function del($ids = "")
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $results =  EmployeeManager::destroySys($item->id,false);
                if ($results['code'] != EmployeeManager::$successCode){
                    throw new Exception($results['message']);
                }
                $count ++ ;
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }

}
